<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午12:03
 *
 * 会员类
 */

use LaravelBook\Ardent\Ardent;

class Member extends Ardent{

    private $integralAccount = null;

    public static $rules = array(
        'name' => 'required|between:1,50',
        'unique_id' => 'required',
    );

    public static $relationsData = array(
        'user' => array(self::MORPH_ONE, 'User', 'name' => 'attach'),
        'orders' => array(self::BELONGS_TO, 'Order', 'foreignKey' => 'member_id', 'otherKey' => 'id'),
        'accounts' => array(self::HAS_MANY, 'MemberAccount', 'foreignKey' => 'member_id', 'otherKey' => 'id'),
        'accountLog' => array(self::HAS_MANY, 'MemberAccountLog', 'foreignKey' => 'member_id', 'otherKey' => 'id'),
    );

    public function currentRoleIds(){
        return $this->user->currentRoleIds();
    }

    public function createOrder($foodIds, $counts, $totalPrice){
        $order = new Order();
        if(!$order->createOrder($this->id, $foodIds, $counts, $totalPrice)){
            $this->errors()->merge($order->errors());
            return false;
        }
        $this->clearBasket();

        return $order;
    }

    public function clearBasket(){
        return Basket::where('member_id', $this->id)->delete();
    }

    /**
     * 自助终端身份认证
     * @param $token
     * @return bool
     */
    public function checkSignature($token){
        return $token == $this->getSignature($token, $this->unique_id);
    }

    /**
     * 自助终端获取认证串
     * @param $token
     * @return string
     */
    public function getSignature($token){
        $tmpArr = array($token, $this->unique_id);

        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        return sha1( $tmpStr );
    }

    /**
     * 获取当前会员账户信息
     *
     * @param string $accountType
     * @return bool
     */
    public function getAccount($accountType = MemberAccount::INTEGRAL_ACCOUNT){
        $account = new MemberAccount();
        $accountModel = $account->getAccount($this->id, $accountType);
        if(!$accountModel){
            $this->errors()->merge($account->errors());
            return false;
        }
        return $accountModel;
    }

    /**
     * 获取该会员账户余额
     *
     * @param $accountType
     * @return mixed
     */
    public function getAccountLeft($accountType = MemberAccount::INTEGRAL_ACCOUNT){
        $account = $this->getAccount($accountType);
        return $account ? $account->current_money : false;
    }


}